import { UserInfo } from "./components/UserInfo";
import type { ReactNode } from "react";
import { useOutlet } from "react-router-dom";
import { useEffect } from "react";
import { useAtom } from "jotai";
import {
  setUserLoginAtom,
  setUserLogoutAtom,
  setLoadingAtom,
  isAuthenticatedAtom,
  isLoadingAtom
} from "./store/userStore";
import { setDocumentsListAtom, documentsListAtom } from "./store/documens";
import { DocumentList } from "./components/DocumentList";
import { useNavigate } from "react-router-dom";

function Home() {
  const [, setUserLogin] = useAtom(setUserLoginAtom);
  const [, setUserLogout] = useAtom(setUserLogoutAtom);
  const [, setLoading] = useAtom(setLoadingAtom);
  const [isAuthenticated] = useAtom(isAuthenticatedAtom);
  const [loading] = useAtom(isLoadingAtom);
  const outlet = useOutlet();

  const [, setDocumentsList] = useAtom(setDocumentsListAtom);
  const [documentsList] = useAtom(documentsListAtom);
  const navigate = useNavigate();

  useEffect(() => {
    // 检查 URL 参数中是否有 sessionId（从 SSO 登录重定向过来）
    const urlParams = new URLSearchParams(window.location.search);
    const sessionId = urlParams.get("sessionId");
    const username = urlParams.get("username");

    if (sessionId && username) {
      console.log("从 SSO 重定向过来，sessionId:", sessionId, "用户:", username);

      // 设置用户登录状态
      setUserLogin({
        user: {
          id: "sso-user",
          username: username,
          lastLoginAt: new Date().toISOString(),
          loginCount: 1
        },
        session: {
          sessionId: sessionId,
          expiresIn: 86400000,
          loginTime: new Date().toISOString()
        }
      });

      // 清理 URL 参数
      window.history.replaceState({}, document.title, window.location.pathname);
      setLoading(false);
      return;
    }

    loginValidate();
  }, []);

  function loginValidate() {
    setLoading(true);

    fetch("/api/sso/validate", {
      method: "GET",
      credentials: "include" // 确保包含cookies
    })
      .then(res => {
        if (!res.ok) {
          throw new Error(`HTTP ${res.status}: ${res.statusText}`);
        }
        return res.json();
      })
      .then(data => {
        console.log("验证响应:", data);

        if (data.success) {
          console.log("登录验证成功", data);

          // 使用 Jotai 设置用户登录状态
          if (data.data && data.data.user && data.data.sessionInfo) {
            setUserLogin({
              user: data.data.user,
              session: data.data.sessionInfo
            });
            console.log("用户状态已更新:", data.data.user.username);
            getDocumentList();
          } else {
            console.warn("服务器返回的用户数据不完整，使用默认值");
            setUserLogin({
              user: {
                id: "unknown",
                username: "unknown",
                lastLoginAt: new Date().toISOString(),
                loginCount: 0
              },
              session: {
                sessionId: "unknown",
                expiresIn: 86400000,
                loginTime: new Date().toISOString()
              }
            });
          }
        } else {
          console.log("登录验证失败:", data.message || "未知错误");
          setUserLogout();

          // 如果未登录，重定向到登录页面
          if (data.code === "NOT_LOGGED_IN" && data.redirectUrl) {
            console.log("用户未登录，准备重定向到:", data.redirectUrl);
            setTimeout(() => {
              window.location.href = data.redirectUrl;
            }, 2000); // 延迟2秒，让用户看到提示
          }
        }
      })
      .catch(e => {
        console.error("验证过程中发生错误:", e);
        setUserLogout();

        // 网络错误或服务器错误的情况下，也尝试重定向到登录页
        if (e.message.includes("Failed to fetch") || e.message.includes("HTTP 50")) {
          console.log("网络或服务器错误，将重定向到登录页");
          setTimeout(() => {
            window.location.href = "http://localhost:5173/";
          }, 3000);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }

  function getDocumentList() {
    console.log(111);

    fetch("/api/documents", {
      method: "GET",
      credentials: "include" // 确保包含cookies
    })
      .then(res => {
        if (!res.ok) {
          throw new Error(`HTTP ${res.status}: ${res.statusText}`);
        }
        return res.json();
      })
      .then(data => {
        console.log(data);
        if (data.success) {
          setDocumentsList(data.data);
        }
      })
      .catch(error => {
        console.error("获取文档列表失败:", error);
      });
  }

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-gray-50">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
        <div className="text-lg text-gray-700">正在验证用户身份...</div>
        <div className="text-sm text-gray-500 mt-2">请稍候</div>
      </div>
    );
  }

  if (!isAuthenticated) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-gray-50">
        <div className="bg-white shadow-lg rounded-lg p-8 max-w-md w-full mx-4">
          <div className="text-center">
            <div className="text-6xl mb-4">🔒</div>
            <div className="text-2xl font-semibold mb-4 text-gray-800">需要登录</div>
            <div className="text-gray-600 mb-6">您需要先登录才能访问富文本编辑器</div>
            <button
              onClick={() => (window.location.href = "http://localhost:5174/")}
              className="w-full px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors font-medium"
            >
              前往登录页面
            </button>
            <div className="text-xs text-gray-500 mt-4">如果您已经登录，页面将自动跳转</div>
          </div>
        </div>
      </div>
    );
  }

  const createDoc = () => {
    fetch(`/api/documents`, {
      method: "POST",
      credentials: "include",
      body: JSON.stringify({
        title: "文档" + Math.random()
      }),
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(res => {
        if (!res.ok) {
          throw new Error(`HTTP ${res.status}: ${res.statusText}`);
        }
        return res.json();
      })
      .then(data => {
        if (data.success) {
          navigate(`/doc/${data.data.id}`);
        }
      });
  };

  return (
    <div className="relative min-h-screen">
      <div className="absolute top-[10px] left-[20px] flex gap-2 z-1000">
        <div
          className="px-4 py-2 text-[14px] bg-[#0ea43b] text-white text-center leading-[26px] border border-[#0ea43b] rounded-[8px] cursor-pointer hover:bg-[#0c8a32] transition-colors"
          onClick={createDoc}
        >
          创建文档
        </div>
        <div
          className="px-4 py-2 text-[14px] bg-[#1890ff] text-white text-center leading-[26px] border border-[#1890ff] rounded-[8px] cursor-pointer hover:bg-[#096dd9] transition-colors"
          onClick={() => navigate("/project-management")}
        >
          项目管理
        </div>
        <div
          className="px-4 py-2 text-[14px] bg-[#722ed1] text-white text-center leading-[26px] border border-[#722ed1] rounded-[8px] cursor-pointer hover:bg-[#531dab] transition-colors"
          onClick={() => navigate("/okr-tree")}
        >
          OKR关系树
        </div>
      </div>
      <UserInfo />
      <DocumentList docList={documentsList} />
      {outlet as ReactNode}
    </div>
  );
}

export default Home;
